package yxy.game.pm2.command.bandit;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.BanditMessage;
import yxy.game.pm2.module.bandit.Bandit;
import yxy.game.pm2.module.bandit.BanditHandle;
import yxy.game.pm2.module.bandit.BanditModule;
import yxy.game.pm2.module.hero.HeroHandle;

import java.util.Collection;

/** 剿匪 剿匪进度获取 */
@MessageType(proto = Command.BanditProgressAcquire, classtype = BanditMessage.BanditProgressAcquireRequest.class)
public class CMD_BanditProgressAcquire extends Command<BanditMessage.BanditProgressAcquireRequest> {

	@Override
	public void execute(MessageSource messageSource, BanditMessage.BanditProgressAcquireRequest request) {
		String playerCode = messageSource.getTag();

		BanditMessage.BanditProgressAcquireResponse.Builder response = BanditMessage.BanditProgressAcquireResponse.newBuilder();

		BanditModule banditModule = BanditModule.get(playerCode);

		response.setRefreshfree(banditModule.freshFreeTimes());
		response.setRefreshtimes(Long.valueOf(banditModule.freshItem().getNumber()).intValue());
		for (Bandit bandit : banditModule.getTaskList()) {
			if (bandit.getDataId() <= 0) {
				continue;
			}
			BanditMessage.BanditTask.Builder task = BanditMessage.BanditTask.newBuilder();
			task.setId(bandit.getDataId());
			if (bandit.getEndTime() != null) {
				task.setTime(bandit.getEndTime().getMillis());
			} else {
				task.setTime(0);
			}
			if (bandit.getSendingHeroCode() != null) {
				for (String heroCode : bandit.getSendingHeroCode()) {
					response.addSending(heroCode);
				}
			}
			response.addTasks(task);
		}
		HeroHandle handle = new HeroHandle();
		Collection<Hero> heros = handle.getHeros(playerCode);
		for (Hero hero : heros) {
			try {
				response.addHeros(handle.getHeroSimple(playerCode, hero));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		send(messageSource, response, Result.Success);
		
		new BanditHandle().updateBanditTip(playerCode);
	}

	private void send(MessageSource messageSource, BanditMessage.BanditProgressAcquireResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}